import { _decorator, Component, AudioSource, AudioClip, resources, director } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('AudioManager')
export class AudioManager extends Component {
    private static _instance: AudioManager = null;
    public static get instance(): AudioManager {
        return AudioManager._instance;
    }

    @property(AudioSource)
    public bgmSource: AudioSource = null;

    @property(AudioSource)
    public sfxSource: AudioSource = null;

    // 音量控制
    private _bgmVolume: number = 1.0;
    private _sfxVolume: number = 1.0;
    private _muted: boolean = false;

    // 音频缓存
    private audioCache: Map<string, AudioClip> = new Map();

    onLoad() {
        if (AudioManager._instance === null) {
            AudioManager._instance = this;
            // 设置为常驻节点，切换场景时不销毁
            director.addPersistRootNode(this.node);
        } else {
            this.node.destroy();
            return;
        }
    }

    start() {
        // 初始化音频源
        if (!this.bgmSource) {
            this.bgmSource = this.node.addComponent(AudioSource);
        }
        if (!this.sfxSource) {
            this.sfxSource = this.node.addComponent(AudioSource);
        }
    }

    /**
     * 播放背景音乐
     * @param clip 音频剪辑或路径
     * @param loop 是否循环
     */
    public playBGM(clip: AudioClip | string, loop: boolean = true,BGMVol:number=0.5) {
        if (typeof clip === 'string') {
            this.loadAudio(clip, (audioClip) => {
                this.playBGMInternal(audioClip, loop,BGMVol);
            });
        } else {
            this.playBGMInternal(clip, loop,BGMVol);
        }
    }

    private playBGMInternal(clip: AudioClip, loop: boolean,BGMVol:number) {
        if (this.bgmSource && clip) {
            this._bgmVolume = BGMVol;
            this.bgmSource.stop();
            this.bgmSource.clip = clip;
            this.bgmSource.loop = loop;
            this.bgmSource.volume = this._muted ? 0 : this._bgmVolume;
            this.bgmSource.play();
        }
    }

    /**
     * 播放音效
     * @param clip 音频剪辑或路径
     * @param loop 是否循环
     */
    public playSFX(clip: AudioClip | string, loop: boolean = false,sfxVol:number=1) {
        if (typeof clip === 'string') {
            this.loadAudio(clip, (audioClip) => {
                this.playSFXInternal(audioClip, loop,sfxVol);
            });
        } else {
            this.playSFXInternal(clip, loop,sfxVol);
        }
    }

    private playSFXInternal(clip: AudioClip, loop: boolean,sfxVol) {
        if (this.sfxSource && clip) {
            this._sfxVolume = sfxVol;
            // 创建新的AudioSource用于音效，允许多个音效同时播放
            const sfxSource = this.node.addComponent(AudioSource);
            sfxSource.clip = clip;
            sfxSource.loop = loop;
            sfxSource.volume = this._muted ? 0 : this._sfxVolume;
            sfxSource.play();
            
            // 如果不循环，播放完成后销毁组件
            if (!loop) {
                setTimeout(() => {
                    if (sfxSource && sfxSource instanceof AudioSource) {
                        this.node.removeComponent(sfxSource);
                    }
                }, clip.getDuration() * 1000 + 100);
            }
        }
    }

    /**
     * 加载音频资源
     * @param path 音频路径
     * @param callback 加载完成回调
     */
    private loadAudio(path: string, callback: (clip: AudioClip) => void) {
        if (this.audioCache.has(path)) {
            callback(this.audioCache.get(path));
            return;
        }

        resources.load(path, AudioClip, (err, clip) => {
            if (err) {
                console.error('Failed to load audio:', path, err);
                return;
            }
            this.audioCache.set(path, clip);
            callback(clip);
        });
    }

    /**
     * 设置背景音乐音量
     * @param volume 音量 (0-1)
     */
    public setBGMVolume(volume: number) {
        this._bgmVolume = Math.max(0, Math.min(1, volume));
        if (this.bgmSource) {
            this.bgmSource.volume = this._muted ? 0 : this._bgmVolume;
        }
    }

    /**
     * 设置音效音量
     * @param volume 音量 (0-1)
     */
    public setSFXVolume(volume: number) {
        this._sfxVolume = Math.max(0, Math.min(1, volume));
        // 音效音量设置会影响后续播放的音效
    }

    /**
     * 设置静音
     * @param muted 是否静音
     */
    public setMuted(muted: boolean) {
        this._muted = muted;
        if (this.bgmSource) {
            this.bgmSource.volume = muted ? 0 : this._bgmVolume;
        }
    }

    /**
     * 暂停背景音乐
     */
    public pauseBGM() {
        if (this.bgmSource && this.bgmSource.playing) {
            this.bgmSource.pause();
        }
    }

    /**
     * 恢复背景音乐
     */
    public resumeBGM() {
        if (this.bgmSource && !this.bgmSource.playing) {
            this.bgmSource.play();
        }
    }

    /**
     * 停止背景音乐
     */
    public stopBGM() {
        if (this.bgmSource) {
            this.bgmSource.stop();
        }
    }

    /**
     * 获取背景音乐音量
     */
    public getBGMVolume(): number {
        return this._bgmVolume;
    }

    /**
     * 获取音效音量
     */
    public getSFXVolume(): number {
        return this._sfxVolume;
    }

    /**
     * 是否静音
     */
    public isMuted(): boolean {
        return this._muted;
    }

    /**
     * 释放音频资源
     * @param path 音频路径，不传则释放所有资源
     */
    public releaseAudio(path?: string) {
        if (path) {
            if (this.audioCache.has(path)) {
                this.audioCache.delete(path);
            }
        } else {
            this.audioCache.clear();
        }
    }
}